package jssia.database.verification;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

import jssia.database.mysql.constants.Collation;
import jssia.database.mysql.constants.TableEngine;

class TableSchema {

    private final String name;
    private final TableEngine engine;
    private final Collation collation;
    private final Map<String, ColumnSchema> columns = new LinkedHashMap<String, ColumnSchema>();

    public TableSchema(String name, TableEngine engine, Collation collation) {
        this.name = name;
        this.engine = engine;
        this.collation = collation;
    }

    public TableSchema(String name, String engine, String collation) {
        this.name = name;
        try {
            this.engine = TableEngine.valueOf(engine.toUpperCase());
        } catch(IllegalArgumentException e) {
            throw new IllegalArgumentException("The database engine " + engine
                    + " does not exist in " + TableEngine.class, e);
        }
        try {
            this.collation = Collation.valueOf(collation.toUpperCase());
        } catch(IllegalArgumentException e) {
            throw new IllegalArgumentException("The collation " + collation
                    + " does not exist in " + Collation.class, e);
        }
    }

    public String getName() {
        return name;
    }

    public TableEngine getEngine() {
        return engine;
    }

    public Collation getCollation() {
        return collation;
    }

    public void addColumn(ColumnSchema column) {
        columns.put(column.getName(), column);
    }

    public ColumnSchema getColumn(String columnName) {
        return columns.get(columnName);
    }

    public ColumnSchema removeColumn(String columnName) {
        return columns.remove(columnName);
    }

    public int numColumns() {
        return columns.size();
    }

    public Collection<ColumnSchema> getAllColumns() {
        return columns.values();
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Table [name=").append(name).append(", engine=")
                .append(engine).append(", collation=").append(collation)
                .append(", columns=\n").append(columns).append("]");
        return builder.toString();
    }
}
